package com.rbcs.flow.webapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.rbcs.flow.FlowConstants;
import com.rbcs.flow.model.Node;
import com.rbcs.flow.service.NodeManager;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.ApplicationException;
import com.systop.core.Constants;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.JsonCrudAction;

/**
 * 流程节点管理Action
 * 
 * @author ShangHua,Nice
 * 
 */
@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class NodeAction extends JsonCrudAction<Node, NodeManager> {

	// JSON数据
	private Map<String, String> auditResult;

	// 开始时间
	private Date startDate;

	// 结束时间
	private Date endDate;

	// 财务节点审核原始单据类别
	private String financeNodeType;

	// 公用查询语句
	private StringBuffer hql = new StringBuffer("from Node n ");

	/**
	 * 部门借款待审信息,部门负责人调用
	 * 
	 * @return
	 */
	public String borrowDeptIndex() {
		hql.append("where n.flow.borrow is not null and n.flow.borrow.project is null ");
		commonQuery(hql);
		return "borrowDeptIndex";
	}

	/**
	 * 项目借款待审信息,项目负责任调用
	 * 
	 * @return
	 */
	public String borrowProjectIndex() {
		hql.append("where n.flow.borrow is not null and n.flow.borrow.project is not null ");
		commonQuery(hql);
		return "borrowProjectIndex";
	}

	/**
	 * 部门报销待审信息,部门负责人调用
	 * 
	 * @return
	 */
	public String reimbDeptIndex() {
		hql.append("where n.flow.reimb is not null and n.flow.reimb.project is null ");
		commonQuery(hql);
		return "reimbDeptIndex";
	}

	/**
	 * 项目报销审核,项目负责人调用
	 * 
	 * @return
	 */
	public String reimbProjectIndex() {
		hql.append("where n.flow.reimb is not null and n.flow.reimb.project is not null ");
		commonQuery(hql);
		return "reimbProjectIndex";
	}

	/**
	 * 部门预算待审核信息
	 * 
	 * @return
	 */
	public String budgetDeptIndex() {
		hql.append("where n.flow.budget is not null ");
		commonQuery(hql);
		getRequest().setAttribute("isDept", true);
		return "budgetDeptIndex";
	}
	
	/**
	 * 项目预算待审核信息
	 * @return
	 */
	public String budgetProjectIndex(){
		hql.append("where n.flow.projectBudget is not null ");
		commonQuery(hql);
		getRequest().setAttribute("isProject", true);
		return "budgetProjectIndex";
	}

	/**
	 * 财务节点审核列表，全部待审节点
	 * 
	 * @return
	 */
	public String financeNodeIndex() {
		StringBuffer hql = new StringBuffer("from Node n where n.dept is null and n.isFinance = '1' ");
		if (FlowConstants.FLOW_BORROW.equals(financeNodeType)) {// 借款
			hql.append("and n.flow.borrow is not null ");
		} else if (FlowConstants.FLOW_REIMB.equals(financeNodeType)) {// 报销
			hql.append("and n.flow.reimb is not null ");
		} else if (FlowConstants.FLOW_BUDGET.equals(financeNodeType)) {// 预算
			hql.append("and n.flow.budget is not null ");
		}else if (FlowConstants.FLOW_BUDGET_PROJECT.equals(financeNodeType)) {// 预算
			hql.append("and n.flow.projectBudget is not null ");
		}else{
			throw new ApplicationException("访问请求类型错误!");
		}
		List<Object> args = new ArrayList<Object>();
		buildCondition(hql, args);
		page = PageUtil.getPage(getPageNo(), getPageSize());
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		return financeNodeType + "FinanceIndex";
	}

	/**
	 * 通用审核节点信息查询
	 * 
	 * @param hql
	 * @return
	 */
	private void commonQuery(StringBuffer hql) {
		List<Object> args = new ArrayList<Object>();
		User user = UserUtil.getLoginUser(getRequest());
		hql.append("and n.auditorIds like ? ");// 查询审核人
		args.add(MatchMode.ANYWHERE.toMatchString(user.getId().toString()));
		buildCondition(hql, args);
		page = PageUtil.getPage(getPageNo(), getPageSize());
		page = getManager().queryPaddingNodes(page, hql.toString(),
				args.toArray());
		for (Object node : page.getData()) {// 设置显示当前登录审批人姓名高亮
			((Node) node).resetAuditorNames(user.getName());
		}
		restorePageData(page);
	}

	private void buildCondition(StringBuffer hql, List<Object> args) {
		if (StringUtils.isNotBlank(getModel().getStatus())) {
			hql.append("and n.status = ? ");
			args.add(getModel().getStatus());
		}
		if (startDate != null) {
			hql.append("and n.flow.createDate >= ? ");
			args.add(startDate);
		}
		if (endDate != null) {
			hql.append("and n.flow.createDate <= ? ");
			args.add(endDate);
		}
		hql.append("order by n.status desc, n.flow.createDate");
	}

	private void buildDate() {
		if (getModel().getId() != null) {
			getModel().setAudDate(new Date());
		}
	}

	/**
	 * 预算,部门审核
	 * 
	 * @return
	 */
	public String budgetAudit() {
		buildDate();
		return "budgetAudit";
	}

	/**
	 * 借款,部门审批
	 */
	public String borrowAudit() {
		buildDate();
		return "borrowAudit";
	}

	/**
	 * 报销,部门审批
	 */
	public String reimbAudit() {
		buildDate();
		return "reimbAudit";
	}

	/**
	 * 节点审核
	 * 
	 * @return
	 */
	public String saveAuditNode() {
		if (getModel() != null && getModel().getId() != null) {
			getModel().setAuditor(UserUtil.getLoginUser(getRequest()));
			getModel().setAudDate(new Date());
			getManager().auditNode(getModel());
		
		}
		if (getModel().getFlow().getBorrow() != null) {// 借款
			if (getModel().getDept() != null ){
				return "borrowDeptNodeIndex";	
			} else {
				if (getModel().getIsFinance().equals(Constants.NO)) {
					return "borrowProjectNodeIndex";	
				} else {
					return "borrowFinanceNodeIndex";	
				}
			}		
		} else if (getModel().getFlow().getReimb() != null) {// 报销
			if (getModel().getDept() != null ){
				return "reimbDeptNodeIndex";	
			} else {
				if (getModel().getIsFinance().equals(Constants.NO)) {
					return "reimbProjectNodeIndex";	
				} else {
					return "reimbFinanceNodeIndex";	
				}
			}

		} 

		return INDEX;
	}

	/**
	 * 异步,节点审核
	 */
	public String saveAudit() {
		auditResult = new HashMap<String, String>();
		User auditor = UserUtil.getPrincipal(getRequest());
		if (getModel() != null && getModel().getId() != null) {
			if (auditor != null) {
				getModel().setAuditor(auditor);
				getModel().setAudDate(new Date());
				getManager().auditNode(getModel());
				auditResult.put("result", "success");
			} else {
				auditResult.put("msg", "用户未登录");
				auditResult.put("result", "error");
			}
		} else {
			auditResult.put("msg", "数据加载失败");
			auditResult.put("result", "error");
		}

		return "jsonRst";
	}

	/**
	 * 显示审批状态
	 */
	public Map<String, String> getAuditStatusMap() {
		return FlowConstants.AUDIT_STATUS_MAP;
	}

	/**
	 * 审批是否通过
	 */
	public Map<String, String> getStatusMap() {
		return FlowConstants.STATUS_MAP;
	}

	/**
	 * return
	 */
	public Map<String, String> getAuditResult() {
		return auditResult;
	}

	public void setAuditResult(Map<String, String> auditResult) {
		this.auditResult = auditResult;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getFinanceNodeType() {
		return financeNodeType;
	}

	public void setFinanceNodeType(String financeNodeType) {
		this.financeNodeType = financeNodeType;
	}
}
